﻿using MongoDB.Driver;
using MongoDB.Driver.GridFS;
using System.Collections.Concurrent;
using System.Configuration;

namespace ldhWebApiWF.database
{
    public class BaseManager
    {
        static MongoClient client;
        static IMongoDatabase db;
        static ConcurrentDictionary<string, dynamic> colls = new ConcurrentDictionary<string, dynamic>();
        public static dynamic GetClient<T>(string dbName, string colName)
        {
            if (client == null || db ==null)
            {
                client = new MongoClient(ConfigurationManager.AppSettings["mongodb"]);
                db = client.GetDatabase(dbName);
            }
            colls.TryAdd(colName, db.GetCollection<T>(colName));
            return colls[colName];
        }

        public static IGridFSBucket GetGridFSBucket(string dbName)
        {
            if (client == null || db == null)
            {
                client = new MongoClient(ConfigurationManager.AppSettings["mongodb"]);
                db = client.GetDatabase(dbName);
            }
            object obj;
            if (!colls.TryGetValue("bucket", out obj))
            {
                var bucket = new GridFSBucket(db, new GridFSBucketOptions
                {
                    BucketName = "jacBucket",
                    ChunkSizeBytes = 1048576 * 10,//10M 
                    WriteConcern = WriteConcern.WMajority,
                    ReadPreference = ReadPreference.Secondary
                });
                colls.TryAdd("bucket", bucket);
            }
            obj = null;
            return colls["bucket"];
        }

    }
}
